package com.sysu.homework.DAO.Impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.sysu.homework.DAO.HomeworkResultDAO;
import com.sysu.homework.model.HomeworkResult;
import com.sysu.homework.model.Student;

@Component("homeworkResultDAO")
public class HomeworkResultDAOImpl implements HomeworkResultDAO {

	private HibernateTemplate hibernateTemplate;
	
	@Override
	public int saveOrUpdate(HomeworkResult homeworkResult) {
		if(homeworkResult.getId()>0){
			int id = homeworkResult.getId();
			System.out.println(id);
			HomeworkResult result =(HomeworkResult)hibernateTemplate.get(HomeworkResult.class, id);
			hibernateTemplate.delete(result);
			hibernateTemplate.flush();
		}
		hibernateTemplate.save(homeworkResult);
		return 1;
	}

	@Override
	public HomeworkResult getHomeworkResultByFilename(String filename) {
		List<HomeworkResult> results = new ArrayList<HomeworkResult>();
		results = hibernateTemplate.find("from HomeworkResult result where result.filename='"+filename+"'");
		if(results.size()>0) {
			return results.get(0);
		}
		return null;
	}

	@Override
	public List<HomeworkResult> getHomeworkResults() {
		List<HomeworkResult> results = new ArrayList<HomeworkResult>();
		results = hibernateTemplate.find("from HomeworkResult r order by r.homework.id");
		return results;
	}

	@Override
	public List<HomeworkResult> getHomeworkResultsByStudentId(int studentid) {
		List<HomeworkResult> results = new ArrayList<HomeworkResult>();
		results = hibernateTemplate.find("from HomeworkResult result where result.student.id='"+studentid+"'");
		return results;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Override
	public List<HomeworkResult> getHomeworkResultsByGroupId(int groupid) {
		List<Student> students = new ArrayList<Student>();
		List<HomeworkResult> results = new ArrayList<HomeworkResult>();
		students = hibernateTemplate.find("from Student s where s.group.id='"+groupid+"'");
		
		for (int i =0;i<students.size();i++) {
			results.addAll(hibernateTemplate.find("from HomeworkResult result " +
					"where result.student.id='"+students.get(i).getId()+"' order by result.homework.id"));
		}
		return results;
	}

	@Override
	public boolean isExistsResult(int homeworkid, int studentid) {
		List<HomeworkResult> results = new ArrayList<HomeworkResult>();
		results = hibernateTemplate.find("from HomeworkResult result where " +
				"result.student.id='"+studentid+"' and result.homework.id='"+homeworkid+"'");
		return (results.size()>0);
	}


}
